package android.bbs.notice;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bbs.notice.Notice_create.ProcessGet;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.utility.Utility;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.example.piano_application.R;

/**
 * 미등록 회원 접속시 처리 화면
 * */
public class Notice_update extends Activity implements OnClickListener{
	ProcessGet processGet;
	ProgressDialog pd; 
	
	private EditText edt_title;
	private EditText edt_contents;
	
	private TextView txv_file;
	private TextView txv_ok;
	
	private int noticeno;
	private String title;
	private String name;
	private String contents;
	private String profilephoto;
	
	private String newtitle;
	private String newname;
	private String newcontents;
	private String newprofilephoto;
	
	
	private String dTime;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notice_update);
        
        Intent intent = getIntent();
        noticeno = intent.getIntExtra("noticeno", 0);
        title = intent.getStringExtra("title");
        name = intent.getStringExtra("name");
        contents = intent.getStringExtra("contents");
        profilephoto = intent.getStringExtra("profilephoto");
        
        txv_ok = (TextView)findViewById(R.id.txv_notice_update_ok);
        txv_ok.setOnClickListener(this);
        
        txv_file = (TextView)findViewById(R.id.txv_notice_update_file);
        txv_file.setText(profilephoto);
        
        edt_title = (EditText)findViewById(R.id.edt_notice_update_title);
        edt_title.setText(title);
        
        edt_contents = (EditText)findViewById(R.id.edt_notice_update_contents);
        edt_contents.setText(contents);
        
        SimpleDateFormat formatter = new SimpleDateFormat ( "yyyyMMdd", Locale.KOREA );
        Date currentTime = new Date ( );
        dTime = formatter.format ( currentTime );
        
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		if (v.getId() == R.id.txv_notice_update_ok) {
			saveData();
		}
	}
	
	public void saveData(){
		newtitle = edt_title.getText().toString();
		newcontents = edt_contents.getText().toString();
		newprofilephoto = txv_file.getText().toString();
		
		newname = Utility.stringToByte(name);
		newtitle = Utility.stringToByte(newtitle);
		newcontents = Utility.stringToByte(newcontents);
		
		pd = ProgressDialog.show(this, "알림", "데이터를 서버에 저장하고 있습니다.");
        
        String addr = NoticeConst.UPDATE + "?noticeno=" + noticeno + "&nickname="+newname + "&title=" + newtitle + "&contents="+ newcontents
        		+ "&profilephoto=" + newprofilephoto + "&noticedate=" + dTime;
        
        processGet = new ProcessGet(addr);
        processGet.start();
	}
	
	class ProcessGet extends Thread{
        String _addr;

        ProcessGet(String addr) {
            _addr = addr;
        }

        public void run() {

            HttpGet get = new HttpGet(_addr);
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                client.execute(get, responseHandler);
            } 
            catch (Exception e) {;}
        }        
    }
    
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) {
 
            StringBuilder html = new StringBuilder(); 
            String message = "";
            try {                
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                br.close();

                JSONObject obj = new JSONObject(html.toString());
                
                String code = obj.getString("code");
                message = obj.getString("message");
                
                if (code.equals("success")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if (code.equals("fail")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 2;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if ( code.equals("error")){
                	Message msg = msgHandler.obtainMessage();
                    msg.what = 3;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                }
            } catch (Exception e) {
                Message msg = msgHandler.obtainMessage();
                msg.what = 4;
                msg.obj = message;
                msgHandler.sendMessage(msg);
            }
            return html.toString();
        }
    };
	
    @SuppressLint("HandlerLeak")
	Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("D", "handleMessage Call");
            
            if (msg.what == 1){
            	Notice_update.this.pd.setMessage( (String)msg.obj); 
                if (Notice_update.this.pd != null){
                	Notice_update.this.pd.dismiss();
                }
                setResult(RESULT_OK, (new Intent()).setAction("SUCCESS")); // "SUCCESS"를 넘겨준다.
            }else if (msg.what == 2){
            	Notice_update.this.pd.setTitle("에러"); 
            	Notice_update.this.pd.setMessage( (String)msg.obj); 
                if (Notice_update.this.pd != null){
                	Notice_update.this.pd.dismiss();
                }
                
            }else if (msg.what == 3){
            	Notice_update.this.pd.setTitle("에러"); 
            	Notice_update.this.pd.setMessage( (String)msg.obj); 
                if (Notice_update.this.pd != null){
                	Notice_update.this.pd.dismiss();
                }
                
            }else if (msg.what == 4){
            	Notice_update.this.pd.setTitle("에러"); 
            	Notice_update.this.pd.setMessage( (String)msg.obj); 
                if (Notice_update.this.pd != null){
                	Notice_update.this.pd.dismiss();
                }
                
            }            
        }
    };
		
}
